//
//  UIColor+HexadecimalColor.m
//  YouYunSDKDemo
//
//  Created by leaves on 14-11-12.
//  Copyright (c) 2014年 网信·有云. All rights reserved.
//

#import "UIColor+HexadecimalColor.h"

@implementation UIColor (HexadecimalColor)

+ (UIColor *)colorWithHexadecimalString:(NSString *)colorValue withColorAlpha:(float)alpha
{
    UIColor *color = [UIColor clearColor];
    if ([[colorValue substringToIndex:1] isEqualToString:@"#"]) {
        if ([colorValue length] == 7) {
            NSRange range = NSMakeRange(1, 2);
            NSString *redString = [colorValue substringWithRange:range];
            range.location = 3;
            NSString *greenString = [colorValue substringWithRange:range];
            range.location = 5;
            NSString *blueString = [colorValue substringWithRange:range];
            
            float r = [UIColor getIntegerFromString:redString];
            float g = [UIColor getIntegerFromString:greenString];
            float b = [UIColor getIntegerFromString:blueString];
            
            color = [UIColor colorWithRed:r/255 green:g/255 blue:b/255 alpha:alpha];
        }
    }
    return color;
}

+ (int) getIntegerFromString:(NSString *)str
{
    int nValue = 0;
    for (int i = 0; i < [str length]; i++)
    {
        int nLetterValue = 0;
        
        if ([str characterAtIndex:i] >='0' && [str characterAtIndex:i] <='9') {
            nLetterValue += ([str characterAtIndex:i] - '0');
        }
        else{
            switch ([str characterAtIndex:i])
            {
                case 'a':case 'A':
                    nLetterValue = 10;break;
                case 'b':case 'B':
                    nLetterValue = 11;break;
                case 'c': case 'C':
                    nLetterValue = 12;break;
                case 'd':case 'D':
                    nLetterValue = 13;break;
                case 'e': case 'E':
                    nLetterValue = 14;break;
                case 'f': case 'F':
                    nLetterValue = 15;break;
                default:nLetterValue = '0';
            }
        }
        
        nValue = nValue * 16 + nLetterValue; //16进制
    }
    return nValue;
}

@end
